import React, {Component} from 'react';
import {InputNumber, Input, Table, DatePicker, message} from 'antd';
import moment from 'moment';


class BiaoZhunForm extends Component {

    constructor(props) {
        super(props);
        this.state = {
            Item: [],//第一列的设置项目变化自动控制
            Data: [],//原始填写的数据
            Time: moment(),//设置的时间
            refresh: true,//提交完后页面刷新
        }
    }

    /**
     * 第一列的设置项变化
     */
    componentWillMount() {
        const allItem = [
            ['KH', 'N', 'P'],
            ['KH', 'N', 'P'],
            ['熟料FCaO', '出磨生料细度', '出磨生料900孔', '出磨生料水分', '入磨生料细度', '入磨生料900孔', '入磨生料水分', '煤粉细度', '煤粉水分'],
            ['KH', 'n', 'p']
        ];
        this.setState({
            Item: [...allItem[this.props.tableChose]],
            Data: this.props.formData,
            standard: this.props.standard,

        });

    }

    componentWillReceiveProps(nextProps) {
        const allItem = [
            ['KH', 'N', 'P'],
            ['KH', 'N', 'P'],
            ['熟料FCaO', '出磨生料细度', '出磨生料900孔', '出磨生料水分', '入磨生料细度', '入磨生料900孔', '入磨生料水分', '煤粉细度', '煤粉水分'],
            ['KH', 'n', 'p']
        ];
        this.setState({
            Item: [...allItem[nextProps.tableChose]],
            Data: nextProps.formData,
            standard: nextProps.standard,
        })
    }

    componentDidMount() {
        //绑定ref
        this.props.onRef(this);
    }

    /**
     * 表格输入数据变化的监听，同时所有的数据更新
     **/
        //event输入框的值，indexF下标的第一个，indexS下标的第二个
    onInputNumberChange2 = (event, indexF, indexS) => {
        let NewData = this.state.Data;
        NewData[indexF][indexS] = event;
        this.setState({
            Data: NewData
        });
    };

    onInputStringChange = (event, indexF, indexS) => {
        if (indexF === 1 && !isNaN(event.target.value)) {

        }
        let newdata = this.state.Data;
        newdata[indexF][indexS] = event.target.value;
        this.setState({
            Data: newdata
        });
    };

    //时间选择框响应
    handleTimeChange = (event) => {
        if (!event) {
            return;
        }
        this.setState({
            Time: event
        })

    };


    postToHome() {
        const {Data, Time} = this.state;//新标准和生效时间
        let standard = this.state.standard;
        let data = [];
        for (let j = 0; j < Data[0].length; j++) {
            data[j] = Data[0][j];
        }
        for (let i = 0; i < standard.length; i++) {
            if (Data[0][i] !== undefined) {//填写了新标准
                if (!Data[1][i]) {//没填写原因
                    message.error('第' + (i + 1) + '行数据未填写修改原因，提交失败');
                    return;
                }
                if (Data[0][i] === standard[i]) {
                    message.error('第' + (i + 1) + '行标准未变化,提交失败');
                    return;
                }
            } else {
                data[i] = standard[i];//对应数据改为之前的标准
            }
        }
        const leixing_list = ['RYS', 'CMS', "KZS", "SSY"];
        const jsondata = {
            'leixing': leixing_list[this.props.tableChose],
            'zhibiao': data + '',
            'yuanyin': Data[1] + '',
            'beizhu': JSON.stringify(Data[2]),
            'createdAt': Time.format('YYYY-MM-DD HH:mm:ss')
        };
        fetch("/api/zhibiao/add", {
            method: 'POST',
            body: JSON.stringify(jsondata), // data can be `string` or {object}!
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
        // .then(data=>console.log(data))
            .then(res => res.json())
            .then(data => {
                if (data['code'] === 0) {
                    message.info('保存成功');
                }
                else if(data['code']===401){
                    message.error('权限不足');
                }
                else if (data['detail']) {
                    message.error('保存失败')
                }
            })
            .catch(error => console.error('Error:', error));
        //更新完新标准后刷新页面原标准数据
        fetch("/api/zhibiao/query", {
            method: 'POST',
            body: JSON.stringify({'leixing': leixing_list[this.props.tableChose]}), // data can be `string` or {object}!
            headers: {
                'Content-Type': 'application/json',
                'authorization': window.localStorage.authorization,
            }
        })
            .then(res => res.json())
            .then(data => {
                if (data['code'] === 0) {
                    const zhibiao = data['zhibiao']['zhibiao'];
                    const standard = zhibiao.split(',');
                    for (let i = 0; i < standard.length; i++) {
                        standard[i] = parseFloat(standard[i]);
                    }
                    this.setState({
                        standard: standard,
                    });
                }
            })
            .catch(error => console.error('Error:', error))
    }

    render() {
        /** 表头**/
        const columns = [
            {
                title: '指标',
                key: 'Item',
                dataIndex: 'Item',
                fixed: 'left',
                width: 100
            },
            {
                title: '原标准(≤)',
                dataIndex: 'OldStandrd',
                key: 'OldStandrd',
                width: '10%',//设置的表格长度
            },
            {
                title: '新标准(≤)',
                key: 'NewStandard',
                dataIndex: 'NewStandard',
                width: '10%',
            },
            {
                title: '生效时间',
                key: 'Time',
                dataIndex: 'Time',
                width: '25%',
            },
            {
                title: '修改原因',
                key: 'Reason',
                dataIndex: 'Reason'
            },
            {
                title: '备注',
                key: 'Remark',
                dataIndex: 'Remark'
            },
        ];

        /**限制输入数值位数的函数**start**/
        const limitDecimals = (value: string | number): string => {
            const reg = /^(\-)*(\d+)\.(\d\d).*$/;
            if (typeof value === 'string') {
                return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : ''
            } else if (typeof value === 'number') {
                return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : ''
            } else {
                return ''
            }
        };
        /**限制输入数值位数的函数**end**/

        const data = [];
        /**表格数据输入**/
        for (let i = 0; i < this.state.Item.length; i++) {
            const Data = this.props.formData;
            data.push(
                {
                    Item: this.state.Item[i],
                    OldStandrd: <span>{this.state.standard[i]}</span>,
                    NewStandard: <InputNumber
                        formatter={limitDecimals}//限制输入数值位数
                        parser={limitDecimals}//限制输入数值位数
                        value={Data[0][i]}
                        step={0.01}
                        style={{width: 'auto'}}
                        onChange={event => this.onInputNumberChange2(event, 0, i)}
                    />,
                    Time: <div>
                        <DatePicker showTime={{format: 'HH:mm'}} value={this.state.Time} format={'YYYY-MM-DD HH:mm'}
                                    onChange={event => this.handleTimeChange(event)}
                        />

                    </div>
                    ,
                    Reason: <Input
                        value={Data[1][i]}
                        onChange={event => this.onInputStringChange(event, 1, i)}
                    />,
                    Remark: <Input
                        value={Data[2][i]}
                        onChange={event => this.onInputStringChange(event, 2, i)}
                    />,
                }
            )
        }

        //数据的自动处理显示部分


        return (
            <div>
                {/*表格填写*/}
                <Table columns={columns} bordered dataSource={data} pagination={false}/>

            </div>
        );
    }

}

export default BiaoZhunForm;